
#include "Socket_TCPIP.h"


///
/// struct part
///



Socket_TCPIP_Info::Socket_TCPIP_Info(int a_nPort, int a_nQueuelength)
{
    port = a_nPort;
    queueLength = a_nQueuelength;
    addr_in = new sockaddr_in();
}

// configure sockaddr_in
int Socket_TCPIP_Info::configSocketAddr()
{
    bzero(addr_in,sizeof(*addr_in));
    addr_in->sin_family = AF_INET;
    addr_in->sin_port = htons(port);
    addr_in->sin_addr.s_addr = htons(INADDR_ANY);
    
    return SOCKET_DEFAULT_SUCCESS;
}

// configure socketlen_t
int Socket_TCPIP_Info::configSocketLen()
{
    // save each sockaddr's length.
    this->len = sizeof(*addr_in);
    return SOCKET_DEFAULT_SUCCESS;
}


///
///  class  part
///


Socket_TCPIP::Socket_TCPIP(struct Socket_TCPIP_Info *a_sInfo):Socket_Base()
{
    this->m_sInfo = a_sInfo;
}

Socket_TCPIP::Socket_TCPIP():Socket_Base()
{
    this->m_sInfo = new Socket_TCPIP_Info(8555, 1500);
}

Socket_TCPIP::Socket_TCPIP(int a_nPort):Socket_Base()
{
    this->m_sInfo = new Socket_TCPIP_Info(a_nPort, 1500);
}

int Socket_TCPIP::socket_bind()
{
    if ((m_sInfo->fd = socket(AF_INET,SOCK_STREAM,0)) < 0)
    {
       printf("create socket error!\n");
       exit(1);
    }

    printf(":::The New Socketfd: %d \n", m_sInfo->fd);
    printf(":::Bind Port: %d \n", m_sInfo->port);
    // configure socketaddr_in
    m_sInfo->configSocketAddr();
    // length
    m_sInfo->configSocketLen();

    if (bind(m_sInfo->fd,(struct sockaddr*)m_sInfo->addr_in, m_sInfo->len)<0)
    {
        printf("bind to port %d failure!\n", m_sInfo->port);
        exit(1);
    }

    printf(":::Socket is ok .... \n");
    
    return SOCKET_DEFAULT_SUCCESS;
}

int Socket_TCPIP::socket_listen()
{
    printf("Socket Listen...Start..\n");
    if (listen(m_sInfo->fd, m_sInfo->queueLength) < 0)
    {
        printf("call listen failure!\n");
        exit(1);
    }
    fprintf(stdout, "Socket Listen...Finish..\n");
}



